package zhangcy.day0110;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义一个Servlet
 */
public class TestServlet extends HttpServlet {
    @Override
    public void init() {
        System.out.println("TestServlet 执行初始化");
    }

    @Override
    public void destroy() {
        System.out.println("TestServlet 执行销毁");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行get请求!");
        // 执行get请求时，调用post请求
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        设置request请求、response响应，中文字符乱码情况
//        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        System.out.println("执行post请求!");
//        创建JspWriter实例对象
        PrintWriter out = response.getWriter();
        out.write("<html>\r\n");
        out.write("<head>\r\n");
        out.write("    <title>初始Servlet</title>\r\n");
        out.write("    ");

//        定义一个Java变量
        String name = "杨雷2号";
//        同一个请求内置对象
        request.setAttribute("elNameRequest", name);
//        使用request请求进行转发scope.jsp页面
//        request.getRequestDispatcher("scope.jsp").forward(request, response);

        out.write("\r\n");
        out.write("</head>\r\n");
        out.write("<body>\r\n");
        out.write("     <h3 style='color:red;'>Hello Servlet!!!</h3>");
        out.write("     <h3 style='color:red;'>你好 Servlet!!!</h3>");
        out.write("</body>\r\n");
        out.write("</html>\r\n");
    }
}
